package db

import (
	"errors"
	"gorm.io/gorm"
	"hr/api/dto"
)

type CompanyProfile struct {
	AppModel
	Describe     string `json:"describe"`
	DescribeText string `json:"describe_text"`
	Tag          string `gorm:"size:128" json:"tag"`
	CreateBy     string `gorm:"size:128" json:"createBy"` // 创建人
	UpdateBy     string `gorm:"size:128" json:"updateBy"` // 更新人
	Remark       string `gorm:"size:255" json:"remark"`   //备注
	Status       string `gorm:"size:64;" json:"status"`
}

func (m *CompanyProfile) TableName() string {
	return "company_profile"
}

type CompanyProfilePageModel struct {
	Total    int64            `json:"total"`
	Result   []CompanyProfile `json:"result"`
	PageNo   int              `json:"pageNo"`
	PageSize int              `json:"pageSize"`
}

func GetCompanyProfilePaging(pagination dto.Pagination, name, tag string) (CompanyProfilePageModel, error) {
	result := CompanyProfilePageModel{
		Total:    0,
		Result:   make([]CompanyProfile, 0),
		PageNo:   pagination.PageNo,
		PageSize: pagination.PageSize,
	}
	offset := (pagination.PageNo - 1) * pagination.PageSize
	dbs := GetInstance().Model(&CompanyProfile{}).Where("tag = ?", tag).Order("created_at desc")

	if err := dbs.Offset(offset).Limit(pagination.PageSize).Find(&result.Result).Error; err != nil {
		return result, err
	}
	if err := dbs.Offset(-1).Limit(-1).Count(&result.Total).Error; err != nil {
		return result, err
	}
	return result, nil
}

// GetCompanyProfile 根据条件查找
func GetCompanyProfile(p map[string]interface{}) (CompanyProfile, error, string) {
	f := CompanyProfile{}
	err := GetInstance().Where(p).First(&f).Error
	if err != nil {
		if errors.Is(err, gorm.ErrRecordNotFound) {
			return f, errors.New("查无记录"), "0"
		}
		return f, errors.New(err.Error()), "1"
	}
	return f, nil, "2"
}

func CreateCompanyProfile(p dto.CompanyProfileRequest, user string) (CompanyProfile, error) {
	d := CompanyProfile{
		Describe: p.Describe,
		DescribeText: p.DescribeText,
		CreateBy: user,
		Remark:   p.Remark,
		Tag:      p.Tag,
	}
	if err := GetInstance().Create(&d).Error; err != nil {
		return d, err
	}
	return d, nil
}

func UpdateCompanyProfile(id uint, p dto.CompanyProfileRequest, userId string) (CompanyProfile, error) {
	f := CompanyProfile{
		AppModel: AppModel{
			ID: id,
		},
	}
	err := GetInstance().Model(&f).Updates(CompanyProfile{
		Describe: p.Describe,
		DescribeText: p.DescribeText,
		UpdateBy: userId,
		Remark:   p.Remark,
		Tag:      p.Tag,
	}).Updates(map[string]interface{}{
		"id": id,
	}).Scan(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}

func DeleteCompanyProfile(id uint) (CompanyProfile, error) {
	f := CompanyProfile{}
	err := GetInstance().Unscoped().Where("id = ?", id).Delete(&f).Error
	if err != nil {
		return f, err
	}
	return f, nil
}
